<?php
class BrandsController extends AppController {

	var $name = 'Brands';
    var $uses = array('Brand','BrandUrl','BrandUrlValue','Result','User');
    var $components = array('RequestHandler');
    function beforeFilter()
    {
        Router::url('/', true);
        parent::beforeFilter();
    }
    
    function index()
    {
        
    }
    
	function list_all() {
		
        $this->Brand->recursive = 1;
		
        $this->paginate = array('limit'=>50);
		$this->set('Results', $this->paginate('Result'));       
        
        //$this->set('brandUrls',$this->BrandUrl->activeData());
		
	}


	function add() {
		if (!empty($this->data)) {
			$this->Brand->create();
			if ($this->Brand->save($this->data)) {
				$this->Session->setFlash(__('The brand has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The brand could not be saved. Please, try again.', true));
			}
		}        
        $this->set('brandUrls',$this->BrandUrl->activeDisplayData());
	}


	function admin_index() {
		$this->Brand->recursive = 0;
		$this->set('brands', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid brand', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('brand', $this->Brand->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->Brand->create();
			if ($this->Brand->save($this->data)) {
				$this->Session->setFlash(__('The brand has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The brand could not be saved. Please, try again.', true));
			}
		}
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid brand', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Brand->save($this->data)) {
				$this->Session->setFlash(__('The brand has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The brand could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Brand->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for brand', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Brand->delete($id)) {
			$this->Session->setFlash(__('Brand deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Brand was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
    
    

	function admin_runcron($limit=150) {	
	   set_time_limit(0);
       App::import('Xml');
       App::import('Vendor', 'remoteParser');
	   App::import('Vendor', 'mainParser', array('file' => 'mainParser.php'));
       App::import('Vendor', 'parserInterface', array('file' => 'parserInterface.php'));
       App::import('Vendor', 'commonParser', array('file' => 'commonParser.php'));            
       App::import('Vendor', 'remoteParser');
              
        $parserCore = new RemoteParserComponent();		
        $parserCore->debug_level = RP_DEBUG_LEVEL_ERRORS;        
        $parserCore->connection_timeout = 15;
         
       //include_once('alexa-api.class.php');	   
	   $this->paginate = array('conditions'=>array('Brand.status'=>'approved'),'order'=>array('Brand.id DESC'),'limit'=>$limit);
	   
       $brandUrls = $this->formIdsAsIndex($this->BrandUrl->activeData());
       $brands = $this->paginate('Brand'); //$this->Brand->getActiveBrands();
       $parsedInformations = array();
	   //debug($brandUrls);
       foreach($brands as $brand)
       {                
            foreach($brand['BrandUrlValue'] as $brandUrlValue)
            {
				$system_name = $brandUrls[$brandUrlValue['brand_url_id']]['system_name'];			   
				
				$parser = new MainParserComponent($system_name,$brandUrlValue['url'],$brandUrls[$brandUrlValue['brand_url_id']],array('parser'=>$parserCore));
				if($parsedInformations = $parser->getInfo()){
					$this->BrandUrlValue->id = $brandUrlValue['id'];
					$this->BrandUrlValue->save(array('value'=>$parsedInformations[$brandUrls[$brandUrlValue['brand_url_id']]['attribute']])); 
				 }      
                 unset($parser);        
                	                       
            } 
       }       
       $this->scoring->calculate($brands);	
       $this->Brand->setRanks();	  
	   $this->Session->setFlash('Cron has been executed successfully.');	  	   
	   $this->redirect('/brands/index');
    }
    
    function formIdsAsIndex($records)
    {
        $data = array();
        foreach($records as $record){                 
            $data[$record['BrandUrl']['id']] = $record['BrandUrl'];
        }
        return $data;
    }
    
    function calculatePoints()
    {
        $this->scoring->calculate(); 
        $this -> viewPath = 'brands';
        $this -> render('runcron');    
    }
    
    function admin_upload()
    {
        if (!empty($this->data) &&
             is_uploaded_file($this->data['Brand']['File']['tmp_name'])) {
            $this->data['Brand']['name'] = $this->data['Brand']['File']['name'];
            $this->data['Brand']['type'] = $this->data['Brand']['File']['type'];
            $this->data['Brand']['size'] = $this->data['Brand']['File']['size'];   
			$csvMimeTypes = array('text/comma-separated-values', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel', 'text/anytext');
            if( !in_array($this->data['Brand']['type'],$csvMimeTypes) )
            {
                $this->Session->setFlash('Invalid File type.', 'default', array('class' => 'error'));
                $this->redirect('/brands/upload');
                exit(0);        
            }            
            
            
            if (($handle = fopen($this->data['Brand']['File']['tmp_name'], "r")) !== FALSE) {
                while (($fileData = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $this->Brand->create();
                    $data = array();
                    $data['Brand'] = array();                
                    $data['Brand']['name']=$fileData[0];
                    $data['Brand']['url']=$fileData[1];
                    $data['Brand']['location']=$fileData[2];
                    $data['Brand']['industry']=$fileData[3];
                    $data['Brand']['facebook_url']=$fileData[4];
                    $data['Brand']['twitter_url']=$fileData[5];
                    $this->Brand->save($data);
                    
                }
                fclose($handle);
            }            
            
        }
        $this -> viewPath = 'brands';
        $this -> render('upload'); 

    }
    
    function login(){
        if(!empty($this->data)){
            if($data = $this->User->valid($this->data['Brand']['username'],$this->data['Brand']['password'])){
                $this->Session->write('User.username',$this->data['Brand']['username']);
                $this->Session->write('User.role',$data['User']['role']);
                $this->redirect('/brands/index');
            }
            else {
                $this->Session->setFlash('Username/password may be wrong');
                $this->redirect('/brands/login');
            }
        }
    }
    
    function logout(){
        $this->Session->destroy();
        $this->redirect('/brands/index');
    }
    
    function badge($id){
       Configure::write('debug', 0);
        $this->RequestHandler->setContent('javascript', 'text/javascript');
        $this->RequestHandler->respondAs('javascript');
        $this->layout = 'ajax';
        $this->set('brand',$this->Brand->getBrand($id));
    }
    
    function setRanks(){
        $this->Brand->setRanks();
        $this -> render('logout'); 
    }
}
